"""
事件循环

wait和gather的区别：
    1.gather更加高层（high-level）【优先考虑使用gather】
    2.gather还能将任务分组
"""

import time
import asyncio


async def get_html(url):
    print("start get url")
    # await的用法：await Awaitable
    await asyncio.sleep(2)
    print("end get url")
    return "Apple"


def use_asyncio():
    start_time = time.time()
    # 事件循环
    loop = asyncio.get_event_loop()

    # 并发的方式
    all_task = [get_html("http://www.imooc.com") for i in range(3)]
    loop.run_until_complete(asyncio.gather(*all_task))

    print("耗时：", time.time() - start_time)
    # 输出结果：
    """
    start get url
    start get url
    start get url
    end get url
    end get url
    end get url
    耗时： 2.015568971633911
    """

    group1 = [get_html("http://www.google.com") for i in range(3)]
    group2 = [get_html("http://www.so.com") for i in range(3)]
    loop.run_until_complete(asyncio.gather(*group1, *group2))

    # group1 = asyncio.gather(*group1)
    # group2 = asyncio.gather(*group2)
    # loop.run_until_complete(asyncio.gather(group1, group2))
    # 输出结果：
    """
    start get url
    start get url
    start get url
    start get url
    start get url
    start get url
    end get url
    end get url
    end get url
    end get url
    end get url
    end get url
    """


if __name__ == '__main__':
    use_asyncio()
